# -*- coding: utf-8 -*-
import os
import win32gui, win32ui, win32con, win32api
import time

class ScreenPIC():
    def __init__(self,windowsClassName=None,windowsTitleName=None):
        if windowsClassName==None or windowsClassName==None:
            self.windowsClassName = r"WindowsForms10.Window.8.app.0.2bf8098_r11_ad1"
            self.windowsTitleName = r"FormModelBuilder"
        else:
            self.windowsClassName = windowsClassName
            self.windowsTitleName = windowsTitleName

    def getScreenShot(self,path=None,name=None,hwndID=None):

        if hwndID==None:
            hwnd = win32gui.FindWindow(self.windowsClassName,self.windowsTitleName)
            if not hwnd:
                print('window not found!')
            else:
                pass
                # print hwnd
        else:
            hwnd=hwndID

        win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)

        # 将窗口提到最前
        win32gui.SetForegroundWindow(hwnd)

        hwndDC = win32gui.GetWindowDC(hwnd)

        mfcDC = win32ui.CreateDCFromHandle(hwndDC)
        saveDC = mfcDC.CreateCompatibleDC()

        saveBitMap = win32ui.CreateBitmap()
        (left,top,right,buttom) = win32gui.GetWindowRect(hwnd)

        w = right - left
        h = buttom - top
        saveBitMap.CreateCompatibleBitmap(mfcDC, w , h)

        saveDC.SelectObject(saveBitMap)
        saveDC.BitBlt((0,0),(w, h) , mfcDC, (0,0), win32con.SRCCOPY)

        path = path + "\\" + str(time.strftime('%Y-%m-%d',time.localtime(time.time())))

        if os.path.exists(path) is False:
            os.makedirs(path)

        bmpname = path + '\\' + name + '_' + str(time.strftime('%Y-%m-%d_%H-%M-%S',time.localtime(time.time())))+".jpeg"

        saveBitMap.SaveBitmapFile(saveDC, bmpname)
        return bmpname

if __name__ == '__main__':
    curX, curY = win32gui.GetCursorPos()
    hwndID = win32gui.WindowFromPoint((curX, curY))
    sp = ScreenPIC()
    sp.getScreenShot(path=r'C:\picture',name='test',hwndID=hwndID)
